from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.mail import send_mail

from sforms.forms import NameForm, ContactForm, UploadFileForm, UploadModelFileForm

import datetime

def get_name(request):

    if request.method == 'POST':
        form = NameForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/sforms/thanks/')

    else:
        form = NameForm()

    return render(request, 'sforms/name.html', {'form': form})


def contact(request):

    if request.method == 'GET':
        form = ContactForm()

    elif request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            sender = form.cleaned_data['sender']
            cc_myself = form.cleaned_data['cc_myself']

            recipients = ['shaocf@garena.com', ]

            if cc_myself:
                recipients.append(sender)

            send_mail(subject, message, sender, recipients)

    return render(request, 'sforms/contact.html', dict(form=form))


def upload_file(request):

    if request.method == 'GET':
        form = UploadFileForm()

    elif request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_upload_file(form.cleaned_data['content'])
            return render(request, 'sforms/upload_file_success.html')

    return render(request, 'sforms/upload_file.html', dict(form=form))


def handle_upload_file(f):
    local_file = '/tmp/sforms_upload_file_%s' % datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    with open(local_file, 'w+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)


def upload_file_model_form(request):

    if request.method == 'GET':
        form = UploadModelFileForm()

    elif request.method == 'POST':
        form = UploadModelFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return render(request, 'sforms/upload_file_success.html')

    return render(request, 'sforms/upload_file_model_form.html', dict(form=form))

